<?php

/**
 * @user magein
 * @date 2023/12/4 16:07
 */

namespace magein\sms;

use magein\utils\Result;

class SmsException extends \Exception
{

    public function __construct($message = '', $code = 0, \Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public static function json($message, $code)
    {
        $message = json_encode([
            'code' => $code,
            'msg' => $message,
            'data' => null,
        ], JSON_UNESCAPED_UNICODE);

        throw new self($message, 200);
    }

    public function toArray()
    {
        if ($this->getMessage()) {
            return json_decode($this->getMessage(), true);
        }
        return [];
    }

    public function toResult(): Result
    {
        $data = $this->toArray();

        if ($data) {
            return Result::error($data['msg'] ?? '', intval($data['code'] ?? 0) ?: 1);
        }

        return Result::error();
    }
}